//var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
//	clicksToEdit : 1
//});

// 票据录入明细grid
Ext.define('HIT.view.ApplyFormInvoiceDetail', {
	extend : 'Ext.grid.Panel',
	alias : 'widget.applyforminvoicedetail',
	id : 'applyFormGrid1',
    store: 'ApplyFormInvoiceDetailStore',

	initComponent : function() {
		var me = this;
		Ext.applyIf( me, {
//			autoScroll : true,
			columnLines: true,
			features: [{ftype: 'summary'}],
			plugins: [cellEditing1],
			selType: 'cellmodel', 
			loadMask: true,
			columns : [ {
		   		 xtype: 'gridcolumn',
		         width: 150,
		         align: 'left',
		         dataIndex: 'goodsName',
		         text: Share.T('货物或应税劳务名称'),
		         listeners : {
		        	 click : cellclickText
		         },
		         renderer : render,
		         summaryType: function(records){
		        	 return "<span style='font-size:12px;font-weight:bold'>"+Share.T("合计")+"</span>";
		         }
			 }, {
				 xtype: 'gridcolumn',
		         width: 100,
		         align: 'center',
		         renderer : render,
		         dataIndex: 'goodsModel',
		         text: Share.T('规格型号'),
		         listeners : {
		        	 click : cellclickText
		         }
			 }, {
				 xtype: 'gridcolumn',
		         width: 70,
		         align: 'center',
		         dataIndex: 'goodsUnit',
		         renderer : render,
		         listeners : {
		        	 click : cellclickText
		         },
		         text: Share.T('单位')
			 }, {
				 xtype: 'gridcolumn',
		         width: 70,
		         align: 'center',
		         renderer : render,
		         listeners : {
		        	 click : cellclickText
		         },
		         dataIndex: 'quantity',
		         text: Share.T('数量'),
		         summaryType: function(records){
		        	 var i = 0,
		        	 length = records.length,
		        	 total = 0;
		        	 for (; i < length; ++i) {
		        		 var record = records[i];
		        		 if(record.get('quantity')!=''&&record.get('quantity')!=null){
		        			 total += parseFloat(record.get('quantity'));
		        		 }
		        	 }
		        	 return "<span style='font-size:12px;font-weight:bold'>" + total + "</span>";
		         }
			 }, {
				 xtype: 'gridcolumn',
		         width: 120,
		         align: 'center',
		         dataIndex: 'priceUnit',
		         renderer : render,
		         listeners : {
		        	 click : cellclickText
		         },
		         text: Share.T('单价')
			 }, {
				 xtype: 'gridcolumn',
		         width: 140,
		         align: 'center',
		         dataIndex: 'amount',
		         decimalPrecision : 6,
		         renderer : render,
		         listeners : {
		        	 click : cellclickText
		         },
		         text: Share.T('金额'),
		         summaryType: function(records){
		        	 var i = 0,
		        	 length = records.length,
		        	 total = 0,
		        	 record;					                    
		        	 for (; i < length; ++i) {
		        		 record = records[i];
		        		 if(record.get('amount')!=''&&record.get('amount')!=null){
		        			 total += parseFloat(record.get('amount'));
		        		 }					                        
		        	 }
		        	 TotalAmount = Share.RetainDecimal(total);
		        	 if(total == 0){
		        		 TotalAmount = 0.00;
		        		 return "<span style='font-size:12px;font-weight:bold'>0.00</span>";
		        	 }else{
		        		 return "<span style='font-size:12px;font-weight:bold'>" + Share.fmoney(total, 2) + "</span>";
		        	 }
		         }
			 }, {
				 xtype: 'gridcolumn',
		         width: 130,
		         align: 'center',
		         dataIndex: 'taxRate',
		         renderer : render,
		         listeners : {
		        	 click : cellclickText
		         },
		         text: Share.T('税率')
			 }, {
				 xtype : 'gridcolumn',
		         width : 130,
		         align : 'center',
		         dataIndex : 'taxAmount',
		         renderer : render,
		         text: Share.T('税额')
			 } ]
		});
		/* 背景淡黄色，原值返回 */
		function render(value, cellmeta, record, rowIndex,
				columnIndex, store) {
			cellmeta.style = 'background-color: #FFFF80;';
			return value;
		}
		
		this.callParent(arguments);
		
		// valid check
		//当前编辑行 
		var rowIndex=0;
		
		//货物名称       
		var goodsNameEditor = new Ext.form.ComboBox({
			// --	GOODS_NAME	nvarchar(200)	商品中文名称
			triggerAction : 'query',
			editable : true,
		    msgTarget : 'side',
			maxLength : 200,
			valueField : 'name',
			displayField : 'name',
		 	hideTrigger : true,  
			typeAhead : false,
			queryDelay : 700,
			selectOnFocus : true,
			store : new Ext.data.JsonStore({
				proxy: {
		            type: 'ajax', 
		            url : ctx + '/getGoodsInfoForEnter',
		            params:{},
		            reader: {
		                type: 'json', 
		                totalProperty: '', 
		                root: '' 
		            } 
				}, 
		        fields:['name', 'spec', 'unit', 'price', 'rate'],
		        autoLoad:true 
			}),
			listeners : {
				beforequery : function(e) {//过滤提示
					var combo = e.combo;
					if(!e.forceAll){   
						var value = e.query;   
						combo.store.filterBy(function(record,id){
							var text = record.get(combo.displayField); 
							return (text.indexOf(value)!=-1);  
						});
						combo.expand();   
						return false;   
					}
				},
				select : function(combo, records, index) {
					var grid = Ext.getCmp('applyFormGrid1');
					var recordtoedit = grid.getSelectionModel().getSelection()[0];
//					var num = grid.getStore().indexOf(recordtoedit);
//					cellEditing.startEditByPosition({row: num, column: 4});
					var spec = records[0].raw.spec;
					var unit = records[0].raw.unit;
					var price = records[0].raw.price;
					var rate = records[0].raw.rate;
					recordtoedit.set('goodsModel', spec);
					recordtoedit.set('goodsUnit', unit);
					recordtoedit.set('priceUnit', price);
					recordtoedit.set('taxRate', rate);
				}
			}
		});
		
		//规格      
		var specificationEditor = new Ext.form.TextField({
			// --	SPEC	nvarchar(100)	规格型号
			allowBlank:false,
			msgTarget:'side',
			maxLength : 100,
		 	blankText:Share.T('规格不能为空')
		});
		
		//计价单位      
		var unitEditor = new Ext.form.TextField({
			// --	GOODS_UNIT	nvarchar(20)	商品单位
			allowBlank:false,
			msgTarget:'side',
			maxLength : 20,
		 	blankText:Share.T('计价单位不能为空')
		});
		
		//数量
		var quantityEditor = new Ext.form.NumberField({
			// --	QUANTITY	decimal(18, 6)	数量
			allowBlank:false,
			msgTarget:'side',
			maxValue:10000000000,
			minValue:-10000000000,
			decimalPrecision :6,
			hideTrigger:true,
			allowDecimals:true,
		 	blankText:Share.T('数量不能为空'),
		    validator : function(value) {
		    	if(/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,6})?$/.test(value)){
		    		if(value != 0){
				    	return true;
		     		}
				}
				return Share.T('数量输入有误'); 
		    },
		    listeners:{
		    	blur:function(compo,the,e){       
		    		if(!/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,6})?$/.test(parseFloat(this.getValue()))){
		    			return;
		    		}
		    		var grid = Ext.getCmp('applyFormGrid1');
					var recordtoedit = grid.getStore().getAt(rowIndex);       			
					var Q = parseFloat(this.getValue());
					var P = recordtoedit.get('priceUnit');
					var R = recordtoedit.get('taxRate');
					P = parseFloat(P);
					R = parseFloat(R);
					
					if(P){
						recordtoedit.set('amount', Share.RetainDecimal(Q*P));
		    		}
					if (R) {
						recordtoedit.set('taxAmount', Share.RetainDecimal(Q*P*R));
					}
		    	}
		    }
		});
		//单价
		var priceEditor = new Ext.form.NumberField({
			// --	PRICE_CUR	decimal(18, 6)	本币单价
			allowBlank:false,
			msgTarget:'side',
			maxValue:10000000000,
			minValue:-10000000000,
			decimalPrecision :6,
			hideTrigger:true,
			allowDecimals:true,
		 	blankText:Share.T('单价不能为空'),
		    validator : function(value) {
		     	if(/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,6})?$/.test(value)){
		     		if(value != 0){
				    	return true;
		     		}
				}
				return Share.T('单价输入有误'); 
		    },
		    listeners:{
		    	blur:function(){
		    		if(!/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,6})?$/.test(parseFloat(this.getValue()))){
		    			return;
		    		}
		    		var grid = Ext.getCmp('applyFormGrid1');
					var recordtoedit = grid.getStore().getAt(rowIndex);       			
					var Q = recordtoedit.get('quantity');
					var P = parseFloat(this.getValue());
					var R = recordtoedit.get('taxRate');
					Q = parseFloat(Q);
					R = parseFloat(R);
					// 金额
					if(Q){
						recordtoedit.set('amount',Share.RetainDecimal(Q*P));
		    		}
					// 税额
					if (R) {
						recordtoedit.set('taxAmount',Share.RetainDecimal(Q*P*R));
					}
		    	}
		    }
		});
		
		//金额 
		var amountEditor = new Ext.form.NumberField({
			// --	AMOUNT_CUR	decimal(18, 2)	本币金额
			allowBlank:false,
			msgTarget:'side',
			maxValue : 10000000000,
			minValue : -10000000000,
			decimalPrecision :2,
			hideTrigger:true,
			allowDecimals:true,
		 	blankText:Share.T('金额不能为空'),
		    validator : function(value) {
		    	if(/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/.test(value)){
					return true;
				}
		    	else{
					return Share.T('金额输入有误');
				}
		    },listeners:{
		    	blur:function(){
		    		if(!/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/.test(parseFloat(this.getValue()))){
		    			return;
		    		}
		    		var grid = Ext.getCmp('applyFormGrid1');
					var recordtoedit = grid.getStore().getAt(rowIndex);       			
					var Q = recordtoedit.get('quantity');
					var A = parseFloat(this.getValue());
					var R = recordtoedit.get('taxRate');
					// 单价
					if(Q){
						Q = parseFloat(Q);
						recordtoedit.set('priceUnit', Share.RetainDecimal(A / Q, 6));
		    		}
					// 税额
					if(R){
						R = parseFloat(R);
						recordtoedit.set('taxAmount', Share.RetainDecimal(A * R, 6));
		    		}
		    	}
		    }
		});
		
		//税率      
		var rateEditor = new Ext.form.NumberField({
			// --	TAX_RATE	decimal(18, 6)	税率
			allowBlank:false,
			msgTarget:'side',
			maxValue : 1,
			minValue : 0,
			decimalPrecision :6,
			hideTrigger:true,
			allowDecimals:true,
		 	blankText:Share.T('税率不能为空'),
		    validator : function(value) {
		    	if(/^(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/.test(value)){
					return true;
				}
				return Share.T('税率输入有误'); 
		    },listeners:{
            	blur:function(){
            		if(!/^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/.test(parseFloat(this.getValue()))){
		    			return;
		    		}
		    		var grid = Ext.getCmp('applyFormGrid1');
					var recordtoedit = grid.getStore().getAt(rowIndex);
					var A = parseFloat(recordtoedit.get('amount'));
					var R = parseFloat(this.getValue());
					if (R && A) {
						recordtoedit.set('taxAmount', Share.RetainDecimal(A * R, 6));
					}
            	}
            }
		});

		function cellclickText(arg1, arg2, _rowIndex, _columnIndex, arg4, arg5){
			var obj = this;
			rowIndex = _rowIndex;
			switch(_columnIndex){
    		case 0:
		    	obj.editor = goodsNameEditor; 
				break;
			case 1:
	            obj.editor = specificationEditor;
				break;
			case 2:
	            obj.editor = unitEditor;
				break;
			case 3:
	            obj.editor = quantityEditor;
				break;
			case 4:
	            obj.editor = priceEditor;
				break;
			case 5:
	            obj.editor = amountEditor;
				break;
			case 6:
	            obj.editor = rateEditor;
				break;
			default:
				obj.editor = new Ext.form.Text({
					editable : false,
		       		labelWidth:50
		       	});
			}
		}
	}
});